const AuthHeaderTypeBearer = 'Bearer';

/**
 * Parse string to groups and select only first two elements
 *
 * Example:
 * Your string: 'Bearer eyJ0eX.. example example ...'
 * Result: { scheme: 'Bearer', value: 'eyJ0eX' }
 *
 * @param value - your value to parse
 * @returns scheme with value
 */
export const parseAuthHeader = (value: string) => {
  const re = /(\S+)\s+(\S+)/;
  if (typeof value !== 'string') {
    return null;
  }
  const matches = value.match(re);
  return matches && { scheme: matches[1], value: matches[2] };
};

/**
 * Get token from request header authorization
 *
 * @param authorization - header
 * @returns token
 */
export const bearerTokenFromHeaderAuthorization = (
  authorization: string | null,
): string | null => {
  let token = null;
  if (authorization) {
    const authParams = parseAuthHeader(authorization);
    if (authParams) {
      if (AuthHeaderTypeBearer === authParams.scheme) {
        token = authParams.value;
      }
    }
  }
  return token;
};
